//
//  RGUserPageView.m
//  RedGrass
//
//  Created by 徐良俊 on 2019/3/18.
//  Copyright © 2019 hongcaosp. All rights reserved.
//

#import "RGUserPageView.h"

#import "JXCategoryView.h"
#import "RGUserInfoHeaderView.h"
#import "RGMeInterfaceBulider.h"
#import <AFNetworking/AFNetworking.h>
#import <MBProgressHUD/MBProgressHUD.h>

@interface RGUserPageView ()<GKPageScrollViewDelegate, JXCategoryViewDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) GKPageScrollView      *pageScrollView;

@property (nonatomic, strong) RGUserInfoHeaderView  *headerView;
@property (nonatomic,strong) UILabel *customNavTitleLabel;

@property (nonatomic, strong) UIView                *pageView;
@property (nonatomic, strong) JXCategoryTitleView   *categoryView;
@property (nonatomic, strong) UIScrollView          *scrollView;

@property (nonatomic, strong) NSArray               *titles;
@property (nonatomic, strong) NSArray               *childVCs;

@property (nonatomic,strong) RGUserInfoModel *userModel;

@end

@implementation RGUserPageView

-(instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.pageScrollView];
        [self.pageScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        [self addSubview:self.customNavTitleLabel];
        [_customNavTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(kStatusBarHeight + 5);
            make.centerX.mas_equalTo(self.mas_centerX).mas_offset(0);
        }];
        [self.pageScrollView reloadData];
    }
    return self;
}

-(void)setMeViewDelegate:(id<RGUserPageViewDelegate>)meViewDelegate {
    _meViewDelegate = meViewDelegate;
}

-(void)setUserWorkViewDelegate:(id<RGUserWorkViewDelegate>)userWorkViewDelegate {
    _userWorkViewDelegate = userWorkViewDelegate;
    if (_childVCs.count > 0) {
        UserWorkListViewController *workVC = _childVCs[0];
        workVC.userViewDelegate = userWorkViewDelegate;
        UserWorkListViewController *loveVC = _childVCs[2];
        loveVC.userViewDelegate = userWorkViewDelegate;
    }
}

-(void)setUserDynamicViewDelegate:(id<RGUserDynamicViewDelegate>)userDynamicViewDelegate {
    _userDynamicViewDelegate = userDynamicViewDelegate;
    if (_childVCs.count > 0) {
        UserDynamicViewController *dyVc = _childVCs[1];
        dyVc.userViewDelegate = userDynamicViewDelegate;
    }
}

#pragma mark - GKPageScrollViewDelegate
- (BOOL)shouldLazyLoadListInPageScrollView:(GKPageScrollView *)pageScrollView {
    return NO;
}

- (UIView *)headerViewInPageScrollView:(GKPageScrollView *)pageScrollView {
    return self.headerView;
}

- (UIView *)pageViewInPageScrollView:(GKPageScrollView *)pageScrollView {
    return self.pageView;
}

- (NSArray<id<GKPageListViewDelegate>> *)listViewsInPageScrollView:(GKPageScrollView *)pageScrollView {
    return self.childVCs;
}

- (void)mainTableViewDidScroll:(UIScrollView *)scrollView isMainCanScroll:(BOOL)isMainCanScroll {
    // 导航栏显隐
    CGFloat offsetY = scrollView.contentOffset.y;
    // 0-200 0
    // 200 - KDYHeaderHeigh - kNavBarheight 渐变从0-1
    // > KDYHeaderHeigh - kNavBarheight 1
    CGFloat alpha = 0;
    if (offsetY < 200) {
        alpha = 0;
    }else if (offsetY > (KScreenWidth - kNavBarHeight - 40)) {
        alpha = 1;
    }else {
        alpha = (offsetY - 200) / (KScreenWidth - kNavBarHeight - 40 - 200);
    }
//    self.gk_navBarAlpha = alpha;
//    self.titleView.alpha = alpha;
    self.customNavTitleLabel.alpha = alpha;
    
    [self.headerView scrollViewDidScroll:offsetY withAlpha:alpha];
}

-(void)startFavoriteAnimationWithIsFavorite:(BOOL)isFavorite cellIndex:(NSInteger)index {
    if([_childVCs count] > 0) {
        UserDynamicViewController *dyVC = _childVCs[1];
        [dyVC startFavoriteAnimationWithIsFavorite:isFavorite cellIndex:index];
    }
}

-(void)stopPlayingWhenCurrentVCIsNoteVisiable {
    
}

-(void)updateforwardCountsWhenShareSuccessWithCellIndex:(NSInteger)cellIndex {
    if([_childVCs count] > 0) {
        UserDynamicViewController *dyVC = _childVCs[1];
        [dyVC updateforwardCountsWhenShareSuccessWithCellIndex:cellIndex];
    }
}

-(void)updateCommentCountsWhenCommentSuccessWithCellIndex:(NSInteger)cellIndex {
    if([_childVCs count] > 0) {
        UserDynamicViewController *dyVC = _childVCs[1];
        [dyVC updateCommentCountsWhenCommentSuccessWithCellIndex:cellIndex];
    }
}

-(void)loadData:(NSInteger)userId {
    self.userId = userId;
}

-(void)reloadData {
    [self loadUserData:self.userId];
    for (int i =0; i< 3; i++) {
        [self reloadDataWhenNeedUpdateData:i];
    }
}

-(void)setUserId:(NSInteger)userId {
    _userId = userId;
    if (_childVCs.count > 0) {
        UserDynamicViewController *dy = _childVCs[1];
        dy.userId = userId;
        UserWorkListViewController *work = _childVCs[0];
        work.userId = userId;
        UserWorkListViewController *love = _childVCs[2];
        love.userId = userId;
    }
    [self reloadData];
}

-(void)reloadDataWhenNeedUpdateData:(NSInteger)index {
    NSObject *vc = [_childVCs objectAtIndex:index];
    if ([vc respondsToSelector:@selector(refreshData)]) {
        [vc performSelector:(@selector(refreshData)) withObject:vc];
    }
}

- (void)loadUserData:(NSInteger)userId {
    HttpRequest *quest = [HttpRequest buildRequest:url_userInfo];
    NSDictionary *params = [RGMeInterfaceBulider buildUserInfo:userId];
    AA_WEAK_MAKE(self) weakSelf = self;
    [quest post:params success:^(id data) {
        //        [weakSelf dismissLoading];
        RGUserInfoModel *model = [[RGMessageContactModel alloc] initWithDictionary:[data objectForKey:@"userInfo"] error:nil];
        if (model) {
            RGUserInfoModel *user = [RGUserInfoModel getUserInfo];
            if(user.ID == userId){
                model.token = user.token;
                [RGUserInfoModel storeUserInfo:model];
            }else{
                if([weakSelf.meViewDelegate respondsToSelector:@selector(updatePersonalPageWithNickName:meFollowmTa:)]){
                    NSDictionary *dic = [data objectForKey:@"userInfo"];
                    BOOL meFollowmTa = [[dic objectForKey:@"meFollowmTa"] boolValue];
                    [weakSelf.meViewDelegate updatePersonalPageWithNickName:model.nickname meFollowmTa:meFollowmTa];
                }
            }
            
            weakSelf.userModel = model;
            weakSelf.customNavTitleLabel.text = model.nickname;
            weakSelf.headerView.model = model;
            weakSelf.categoryView.titles = @[[NSString stringWithFormat:@"%ld作品",(long)self->_userModel.worksCount],[NSString stringWithFormat:@"%ld动态",(long)self->_userModel.dynamicCount],[NSString stringWithFormat:@"%ld喜欢",(long)self->_userModel.likeVideoCount]];
            [weakSelf.categoryView reloadData];
        }
    } fail:^(NSInteger code, NSString *message) {
        [MBProgressHUD showTipMessageInView:message];
    }];
}

#pragma mark - JXCategoryViewDelegate
- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"刷新数据");
    if (_childVCs.count > 0) {
        UserDynamicViewController *dynamic = _childVCs[1];
        if(index == 1) {
            [dynamic onShow];
        } else {
            [dynamic onHide];
        }
    }
    
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.pageScrollView horizonScrollViewWillBeginScroll];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self.pageScrollView horizonScrollViewDidEndedScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.pageScrollView horizonScrollViewDidEndedScroll];
}

-(void)setIsShowHeaderViewBtnView:(BOOL)isShowHeaderViewBtnView {
    _isShowHeaderViewBtnView = isShowHeaderViewBtnView;
    if (_headerView) {
        _headerView.isShowBtnView = _isShowHeaderViewBtnView;
    }
}

#pragma mark - 懒加载
- (GKPageScrollView *)pageScrollView {
    if (!_pageScrollView) {
        _pageScrollView = [[GKPageScrollView alloc] initWithDelegate:self];
        _pageScrollView.ceilPointHeight = kNavBarHeight + 40;
    }
    return _pageScrollView;
}

- (RGUserInfoHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[RGUserInfoHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth)];
        _headerView.isShowBtnView = _isShowHeaderViewBtnView;
        AA_WEAK_MAKE(self)weakSelf = self;
        [_headerView setActionBtnClick:^(NSInteger tag) {
            if (weakSelf.meViewDelegate && [weakSelf.meViewDelegate respondsToSelector:@selector(actionBtnClickWithView:)]) {
                [weakSelf.meViewDelegate actionBtnClickWithView:tag];
            }
        }];
        if (_userModel) {
            _headerView.model = _userModel;
        }
        [self.headerView addSubview:self.categoryView];
        [self.categoryView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(self.headerView.mas_width);
            make.height.mas_equalTo(40);
            make.bottom.mas_equalTo(self.headerView.mas_bottom);
            make.left.mas_equalTo(0);
        }];
    }
    return _headerView;
}

- (UIView *)pageView {
    if (!_pageView) {
        _pageView = [UIView new];
        _pageView.backgroundColor = [UIColor clearColor];
        
//        [_pageView addSubview:self.categoryView];
        [_pageView addSubview:self.scrollView];
    }
    return _pageView;
}

- (JXCategoryTitleView *)categoryView {
    if (!_categoryView) {
        _categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 40.0f)];
        _categoryView.backgroundColor = [UIColor clearColor];
        _categoryView.titles = self.titles;
        _categoryView.delegate = self;
        _categoryView.titleColor = [UIColor lightTextColor];
        _categoryView.titleSelectedColor = [UIColor whiteColor];
        _categoryView.titleFont = [UIFont systemFontOfSize:16.0f];
        _categoryView.titleSelectedFont = [UIFont systemFontOfSize:16.0f];
        
        JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
        lineView.indicatorLineViewColor = RGBColor(225, 77, 123);
        lineView.indicatorLineWidth = 30.0f;
        lineView.indicatorLineViewCornerRadius = 2;
        lineView.lineStyle = JXCategoryIndicatorLineStyle_Normal;
        _categoryView.indicators = @[lineView];
        
        _categoryView.contentScrollView = self.scrollView;
        
        // 添加分割线
        UIView *btmLineView = [UIView new];
        btmLineView.frame = CGRectMake(0, 40 - 0.5, KScreenWidth, 0.5);
        btmLineView.backgroundColor = RGBColor(200,200,200);
        [_categoryView addSubview:btmLineView];
    }
    return _categoryView;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        CGFloat scrollW = KScreenWidth;
        CGFloat scrollH = KScreenHeight - kNavBarHeight - 40;
        
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, scrollW, scrollH)];
        _scrollView.pagingEnabled = YES;
        _scrollView.bounces = NO;
        _scrollView.delegate = self;
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.showsHorizontalScrollIndicator = NO;
        
        [self.childVCs enumerateObjectsUsingBlock:^(UIViewController *vc, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.viewController addChildViewController:vc];
            [self->_scrollView addSubview:vc.view];
            
            vc.view.frame = CGRectMake(idx * scrollW, 0, scrollW, scrollH);
        }];
        _scrollView.contentSize = CGSizeMake(self.childVCs.count * scrollW, 0);
        
    }
    return _scrollView;
}

-(UILabel *)customNavTitleLabel{
    if(!_customNavTitleLabel){
        _customNavTitleLabel = [[UILabel alloc]init];
        _customNavTitleLabel.font = FONT(customBoldFontName, FFont_17);
        _customNavTitleLabel.textColor = [UIColor whiteColor];
        _customNavTitleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _customNavTitleLabel;
}

- (NSArray *)titles {
    if (!_titles) {
        _titles = @[@"作品", @"动态", @"喜欢"];
    }
//    @[[NSString stringWithFormat:@"%ld作品",(long)_userModel.worksCount],[NSString stringWithFormat:@"%d动态",_userModel.dynamicCount],[NSString stringWithFormat:@"%d喜欢",_userModel.likeVideoCount]];
    return _titles;
}

- (NSArray *)childVCs {
    if (!_childVCs) {
        UserWorkListViewController *userWorkListVC = [UserWorkListViewController new];
        userWorkListVC.tabIndex = 0;
        userWorkListVC.userViewDelegate = self.userWorkViewDelegate;
        userWorkListVC.userId = self.userId;
        
        UserDynamicViewController *dynamicVC = [UserDynamicViewController new];
        dynamicVC.userViewDelegate = self.userDynamicViewDelegate;
        dynamicVC.userId = self.userId;
        
        UserWorkListViewController *userLoveListVC = [UserWorkListViewController new];
        userLoveListVC.tabIndex = 2;
        userWorkListVC.userViewDelegate = self.userWorkViewDelegate;
        userLoveListVC.userId = self.userId;
        
        _childVCs = @[userWorkListVC, dynamicVC, userLoveListVC];
    }
    return _childVCs;
}

@end
